package com.beiyou.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.beiyou.dao.ImgsMapper;
import com.beiyou.dto.ImgsDto;
import com.beiyou.entity.ImgsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wzby
 * @Date: 2022/10/19 17:08
 */
@Service
public class ImgsService {

    @Autowired
    private ImgsMapper imgsMapper;

    public Integer insert(ImgsDto imgsDto){
        String base64 = imgsDto.getImgBase64();
        String[] dataArray = StrUtil.splitToArray(base64, "base64");
        byte[] bytes = Base64.decode(dataArray[1]);

        String imgName = imgsDto.getImgName();
        imgName = IdUtil.fastSimpleUUID() + "_" + imgName;
        FileUtil.writeBytes(bytes, "D:/JAVA/nginx-1.23.1/html/images/" + imgName);
        //将上传的照片放到指定文件夹下

        ImgsEntity imgsEntity = BeanUtil.copyProperties(imgsDto, ImgsEntity.class);
        imgsEntity.setCreateTime(LocalDate.now());
        imgsEntity.setImg("http://img.211.com/images/" + imgName);
        //  将设置好的图片地址名称存到数据库当中
        return imgsMapper.insert(imgsEntity);
    }

    public List<ImgsDto> select(){
        List<ImgsEntity> imgsEntities = imgsMapper.selectXml();
        List<ImgsDto> dtoList = new ArrayList<>();
        for (ImgsEntity entity : imgsEntities){
            ImgsDto imgsDto = new ImgsDto();
            imgsDto.setId(entity.getId());
            imgsDto.setImg(entity.getImg());
            imgsDto.setCreateTime(entity.getCreateTime());
            dtoList.add(imgsDto);
        }
        return dtoList;
    }

}
